using System;
using UnityEngine;
using UnityEngine.Networking;

namespace HEFramework
{
    public static class HECoroutine
    {
        /// <summary>
        /// 有了这个方法，就可以直接await Unity的AsyncOperation了
        /// </summary>
        /// <param name="_asyncOperation"></param>
        public static async HETask GetAwaiter(this AsyncOperation _asyncOperation)
        {
            HETask task = HETask.Create(true);
            _asyncOperation.completed += _ => { task.SetResult(); };
            await task;
        }

        /// <summary>
        /// 针对网络连接
        /// </summary>
        /// <param name="_link"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async HETask<string> HttpGet(string _link)
        {
            try
            {
                UnityWebRequest req = UnityWebRequest.Get(_link);
                await req.SendWebRequest();
                return req.downloadHandler.text;
            }
            catch (Exception e)
            {
                throw new Exception($"Http request fail: {_link.Substring(0, _link.IndexOf('?'))}\n{e}");
            }
        }
    }
}